package LeetCode_SingleLinkedlist;

/**
 * Created with IntelliJ IDEA.
 * Description:寻找链表中倒数第k个节点
 * User: 阿宾
 * Date: 2024-11-06
 * Time: 11:00
 */
public class Demo3 {
    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
    public static ListNode FindKthToTail(ListNode pHead, int k) {
        // write code here
        ListNode fast = pHead;
        ListNode slow = pHead;
        if(k == 0 || pHead == null){
            return null;
        }

        for (int i = 0; i < k - 1; i++) {
            fast = fast.next;
            if(fast == null){
                return null;
            }
        }

        while (fast.next != null){
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }


    public static void main(String[] args) {
        // 创建测试链表
        ListNode l1 = new ListNode(1, new ListNode(2,new ListNode(4,new ListNode(6,new ListNode(8)))));
        ListNode ret = FindKthToTail(l1,6);

        while (ret != null){
            System.out.print(ret.val + " ");
            ret = ret.next;
        }


    }
}
